package com.atguigu.chapter08;

import com.atguigu.bean.AdsClickLog;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/21 16:23
 */
public class Flink04_High_Project_Blacklist {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 创建WatermarkStrategy
        WatermarkStrategy<AdsClickLog> wms = WatermarkStrategy
            .<AdsClickLog>forBoundedOutOfOrderness(Duration.ofSeconds(20))
            .withTimestampAssigner(new SerializableTimestampAssigner<AdsClickLog>() {
                @Override
                public long extractTimestamp(AdsClickLog element, long recordTimestamp) {
                    return element.getTimestamp() * 1000L;
                }
            });
        
        SingleOutputStreamOperator<String> normal = env
            .readTextFile("input/AdClickLog.csv")
            .map(line -> {
                String[] datas = line.split(",");
                return new AdsClickLog(Long.valueOf(datas[0]),
                                       Long.valueOf(datas[1]),
                                       datas[2],
                                       datas[3],
                                       Long.valueOf(datas[4]));
            })
            .assignTimestampsAndWatermarks(wms)
            .keyBy(log -> log.getUserId() + "_" + log.getAdsId())
            .process(new KeyedProcessFunction<String, AdsClickLog, String>() {
                
                private ValueState<String> yesterdayState;
                private ValueState<Boolean> warnState;
                private ReducingState<Long> countState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    countState = getRuntimeContext()
                        .getReducingState(new ReducingStateDescriptor<Long>("countState",
                                                                            Long::sum,
                                                                            Long.class));
                    
                    warnState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<Boolean>("warnState", Boolean.class));
                    
                    yesterdayState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<String>("yesterdayState", String.class));
                }
                
                @Override
                public void processElement(AdsClickLog log,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    
                    // 如何知道到了第二天, 清空状态
                    String yesterday = yesterdayState.value();
                    String today = new SimpleDateFormat("yyyy-MM-dd").format(log.getTimestamp() * 1000);
                    if (log.getUserId() == 937166) System.out.println(yesterday + "  " + today);
                    if (!today.equals(yesterday)) {
                        if (log.getUserId() == 937166) System.out.println("xxxxx");
                        countState.clear();
                        warnState.clear();
                        yesterdayState.update(today);
                    }
                    
                    // 聚合
                    if (warnState.value() == null) {
                        countState.add(1L);
                    }
                    
                    String msg = "用户: " + log.getUserId() + " 对广告:" + log.getAdsId() + " 的点击量是: " + countState.get();
                    if (countState.get() > 99) {
                        if (warnState.value() == null) {
                            ctx.output(new OutputTag<String>("blackList") {}, msg + " 加入黑名单");
                            warnState.update(true);
                        }
                    } else {
                        out.collect(msg);
                    }
                    
                }
            });
        
        normal.print("normal");
        
        normal.getSideOutput(new OutputTag<String>("blackList") {}).print("black");
        
        env.execute();
        
    }
}
